using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 书籍基本信息管理服务
    /// </summary>
    public interface IBookBasicInfoService
    {
        /// <summary>
        /// 保存书籍基本信息
        /// </summary>
        /// <param name="basicInfo">书籍基本信息</param>
        /// <returns>保存结果</returns>
        Task<(bool Success, string Message)> SaveBasicInfoAsync(BookBasicInfo basicInfo);

        /// <summary>
        /// 加载书籍基本信息
        /// </summary>
        /// <param name="projectPath">项目路径</param>
        /// <returns>书籍基本信息</returns>
        Task<BookBasicInfo?> LoadBasicInfoAsync(string projectPath);

        /// <summary>
        /// 获取所有已保存的书籍基本信息
        /// </summary>
        /// <returns>书籍基本信息列表</returns>
        Task<List<BookBasicInfo>> GetAllSavedBasicInfoAsync();

        /// <summary>
        /// 删除书籍基本信息
        /// </summary>
        /// <param name="projectPath">项目路径</param>
        /// <returns>删除结果</returns>
        Task<(bool Success, string Message)> DeleteBasicInfoAsync(string projectPath);
    }

    /// <summary>
    /// 书籍基本信息管理服务实现
    /// </summary>
    public class BookBasicInfoService : IBookBasicInfoService
    {
        private readonly ILogger<BookBasicInfoService> _logger;
        private readonly string _configDirectory;
        private const string BasicInfoFileName = "book_basic_info.json";
        private const string GlobalConfigFileName = "saved_book_configs.json";

        public BookBasicInfoService(ILogger<BookBasicInfoService> logger)
        {
            _logger = logger;
            _configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                "DocumentCreationSystem", "BookConfigs");
            
            // 确保配置目录存在
            Directory.CreateDirectory(_configDirectory);
        }

        /// <summary>
        /// 保存书籍基本信息
        /// </summary>
        public async Task<(bool Success, string Message)> SaveBasicInfoAsync(BookBasicInfo basicInfo)
        {
            try
            {
                // 验证基本信息
                var (isValid, errorMessage) = basicInfo.Validate();
                if (!isValid)
                {
                    return (false, errorMessage);
                }

                // 保存到项目目录
                if (!string.IsNullOrEmpty(basicInfo.ProjectPath))
                {
                    var projectConfigPath = Path.Combine(basicInfo.ProjectPath, BasicInfoFileName);
                    await SaveToFileAsync(basicInfo, projectConfigPath);
                }

                // 保存到全局配置
                await SaveToGlobalConfigAsync(basicInfo);

                _logger.LogInformation($"书籍基本信息保存成功: {basicInfo.BookTitle}");
                return (true, "书籍基本信息保存成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存书籍基本信息失败");
                return (false, $"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载书籍基本信息
        /// </summary>
        public async Task<BookBasicInfo?> LoadBasicInfoAsync(string projectPath)
        {
            try
            {
                if (string.IsNullOrEmpty(projectPath))
                {
                    return null;
                }

                var configPath = Path.Combine(projectPath, BasicInfoFileName);
                if (!File.Exists(configPath))
                {
                    _logger.LogInformation($"项目配置文件不存在: {configPath}");
                    return null;
                }

                var json = await File.ReadAllTextAsync(configPath);
                var basicInfo = JsonSerializer.Deserialize<BookBasicInfo>(json);

                if (basicInfo != null)
                {
                    basicInfo.ProjectPath = projectPath;
                    _logger.LogInformation($"书籍基本信息加载成功: {basicInfo.BookTitle}");
                }

                return basicInfo;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载书籍基本信息失败: {projectPath}");
                return null;
            }
        }

        /// <summary>
        /// 获取所有已保存的书籍基本信息
        /// </summary>
        public async Task<List<BookBasicInfo>> GetAllSavedBasicInfoAsync()
        {
            try
            {
                var globalConfigPath = Path.Combine(_configDirectory, GlobalConfigFileName);
                if (!File.Exists(globalConfigPath))
                {
                    return new List<BookBasicInfo>();
                }

                var json = await File.ReadAllTextAsync(globalConfigPath);
                var configs = JsonSerializer.Deserialize<List<BookBasicInfo>>(json);

                return configs ?? new List<BookBasicInfo>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取已保存的书籍基本信息失败");
                return new List<BookBasicInfo>();
            }
        }

        /// <summary>
        /// 删除书籍基本信息
        /// </summary>
        public async Task<(bool Success, string Message)> DeleteBasicInfoAsync(string projectPath)
        {
            try
            {
                // 删除项目配置文件
                var projectConfigPath = Path.Combine(projectPath, BasicInfoFileName);
                if (File.Exists(projectConfigPath))
                {
                    File.Delete(projectConfigPath);
                }

                // 从全局配置中移除
                await RemoveFromGlobalConfigAsync(projectPath);

                _logger.LogInformation($"书籍基本信息删除成功: {projectPath}");
                return (true, "书籍基本信息删除成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除书籍基本信息失败: {projectPath}");
                return (false, $"删除失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        private async Task SaveToFileAsync(BookBasicInfo basicInfo, string filePath)
        {
            var directory = Path.GetDirectoryName(filePath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            basicInfo.SavedAt = DateTime.Now;

            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            var json = JsonSerializer.Serialize(basicInfo, options);
            await File.WriteAllTextAsync(filePath, json);
        }

        /// <summary>
        /// 保存到全局配置
        /// </summary>
        private async Task SaveToGlobalConfigAsync(BookBasicInfo basicInfo)
        {
            var configs = await GetAllSavedBasicInfoAsync();
            
            // 移除相同项目路径的旧配置
            configs.RemoveAll(c => c.ProjectPath == basicInfo.ProjectPath);
            
            // 添加新配置
            configs.Add(basicInfo.Clone());
            
            // 按保存时间倒序排列，保留最近的20个
            configs = configs.OrderByDescending(c => c.SavedAt).Take(20).ToList();

            var globalConfigPath = Path.Combine(_configDirectory, GlobalConfigFileName);
            await SaveToFileAsync(configs.First(), globalConfigPath);

            // 保存完整列表
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            var json = JsonSerializer.Serialize(configs, options);
            await File.WriteAllTextAsync(globalConfigPath, json);
        }

        /// <summary>
        /// 从全局配置中移除
        /// </summary>
        private async Task RemoveFromGlobalConfigAsync(string projectPath)
        {
            var configs = await GetAllSavedBasicInfoAsync();
            configs.RemoveAll(c => c.ProjectPath == projectPath);

            var globalConfigPath = Path.Combine(_configDirectory, GlobalConfigFileName);
            
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            var json = JsonSerializer.Serialize(configs, options);
            await File.WriteAllTextAsync(globalConfigPath, json);
        }
    }
}
